<template>
	<view class="container">
		<view class="avatar-section">
			<!-- 修改这里：添加 open-type 和正确的事件名 -->
			<button class="avatar-container" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image :src="user.avatar" class="avatar-image" />
			</button>
		</view>

		<view class="form-list">
			<view class="form-item" @click="editNickName">
				<view class="label">用户昵称</view>
				<view class="value">{{ user.nickName || '请输入昵称' }}</view>
				<view class="arrow">›</view>
			</view>
			<view class="form-item" @click="editBio">
				<view class="label">个人简介</view>
				<view class="value">{{ useradditionalinfo.bio || '介绍一下自己' }}</view>
				<view class="arrow">›</view>
			</view>
		</view>

		<view class="form-list">
			<view class="form-item" @click="editSex">
				<view class="label">性别</view>
				<view class="value">{{ getSexText(user.sex) || '编辑性别' }}</view>
				<view class="arrow">›</view>
			</view>

			<view class="form-item" @click="editEmail">
				<view class="label">邮箱</view>
				<view class="value">{{ user.email || '请输入邮箱' }}</view>
				<view class="arrow">›</view>
			</view>
		</view>

		<view class="save-btn-container">
			<button class="save-btn" @click="submit">保存</button>
		</view>

		<!-- 弹窗组件 -->
		<uni-popup ref="popup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<view class="popup-cancel" @click="closePopup">取消</view>
					<view class="popup-title">{{ currentEditField.title }}</view>
					<view class="popup-confirm" @click="confirmEdit">确定</view>
				</view>
				<view class="popup-body">
					<!-- 昵称输入 -->
					<input v-if="currentEditField.type === 'nickName'" v-model="tempValue" class="input-field"
						placeholder="请输入昵称" />

					<!-- 邮箱输入 -->
					<input v-if="currentEditField.type === 'email'" v-model="tempValue" class="input-field"
						placeholder="请输入邮箱" />

					<!-- 个人简介输入 -->
					<textarea v-if="currentEditField.type === 'bio'" v-model="tempValue" class="textarea-field"
						placeholder="介绍一下自己" />

					<!-- 性别选择 -->
					<view v-if="currentEditField.type === 'sex'" class="sex-options">
						<view v-for="item in sexs" :key="item.value" class="sex-option"
							:class="{ active: tempValue === item.value }" @click="tempValue = item.value">
							{{ item.text }}
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, onUnmounted } from 'vue'
	import {
		getUserProfile,
		updateUserProfile
	} from "@/api/system/user"
	import useUserStore from '@/store/modules/user'
	import {
		updateInfo,
		getInfoByUserId
	} from "@/api/useradditionalinfo/info"
	import { uploadFile } from '@/api/upload/upload'

	// 类型定义
	interface User {
		nickName : string
		phonenumber : string
		email : string
		sex : string
		avatar : string
	}

	interface UserAdditionalInfo {
		birthday ?: string
		bio ?: string
		[key : string] : any
	}

	interface SexOption {
		text : string
		value : string
	}

	interface EditField {
		type : string
		title : string
	}

	// 响应式数据
	const popup = ref()
	const user = reactive<User>({
		nickName: "",
		phonenumber: "",
		email: "",
		sex: "",
		avatar: ""
	})

	const useradditionalinfo = reactive<UserAdditionalInfo>({})
	const tempValue = ref('')
	const currentEditField = reactive<EditField>({
		type: '',
		title: ''
	})

	const sexs : SexOption[] = [
		{
			text: '男',
			value: "0"
		},
		{
			text: '女',
			value: "1"
		}
	]

	// 方法
	const getUser = async () : Promise<void> => {
		try {
			Object.assign(user, useUserStore().user)

			Object.assign(useradditionalinfo, useUserStore().userAdditionalInfo)
		} catch (error) {
			console.error('获取用户信息失败:', error)
		}
	}

	const getSexText = (value : string) : string => {
		const sex = sexs.find(item => item.value === value)
		return sex ? sex.text : ''
	}

	const goBack = () : void => {
		uni.navigateBack()
	}

	const preview = () : void => {
		// 预览功能
		console.log('预览')
	}

	// 编辑方法
	const editNickName = () : void => {
		currentEditField.type = 'nickName'
		currentEditField.title = '用户昵称'
		tempValue.value = user.nickName
		popup.value.open()
	}

	const editEmail = () : void => {
		currentEditField.type = 'email'
		currentEditField.title = '邮箱'
		tempValue.value = user.email
		popup.value.open()
	}

	const editBio = () : void => {
		currentEditField.type = 'bio'
		currentEditField.title = '个人简介'
		tempValue.value = useradditionalinfo.bio || ''
		popup.value.open()
	}

	const editSex = () : void => {
		currentEditField.type = 'sex'
		currentEditField.title = '性别'
		tempValue.value = user.sex
		popup.value.open()
	}

	const closePopup = () : void => {
		popup.value.close()
	}

	const confirmEdit = () : void => {
		if (currentEditField.type === 'nickName') {
			user.nickName = tempValue.value
		} else if (currentEditField.type === 'email') {
			user.email = tempValue.value
		} else if (currentEditField.type === 'bio') {
			useradditionalinfo.bio = tempValue.value
		} else if (currentEditField.type === 'sex') {
			user.sex = tempValue.value
		}
		popup.value.close()
	}

	const onDateChange = (value : string) : void => {
		tempValue.value = value
	}

	// 选择头像方法
	const chooseAvatar = () : void => {
		uni.navigateTo({
			url: '/pages_mine/pages/avatar/index'
		});
	}

	// 修改头像上传方法，参考wxRegister.vue的实现
	const onChooseAvatar = async (e : any) => {
		const { avatarUrl } = e.detail
		if (!avatarUrl) {
			uni.showToast({
				title: '请选择头像',
				icon: 'none'
			})
			return
		}

		// 使用upload.ts的uploadFile方法上传头像
		const response = await uploadFile(avatarUrl, 'minio', 'MASTER')

		if (response.code === 200 && response.url) {
			// 更新用户头像信息到后端
			user.avatar = response.url

			uni.showToast({
				title: '头像更新成功',
				icon: 'success'
			})
		} else {
			throw new Error(response.msg || '上传失败')
		}
	}



	const submit = async () : Promise<void> => {
		try {
			// 更新用户基本信息（包括头像）
			await updateUserProfile(user)

			// 更新用户额外信息
			await updateInfo(useradditionalinfo)

			uni.showToast({
				title: '修改成功',
				mask: false,
				duration: 1000
			})

			const userStore = useUserStore()
			userStore.getInfo()
			uni.$emit('refresh');
			// uni.navigateBack()
			uni.switchTab({
				url: '/pages/mine/mine'
			})

		} catch (error) {
			console.error('更新用户信息失败:', error)
			uni.showToast({
				title: '更新失败',
				icon: 'none',
				duration: 1500
			})
		}
	}

	// 生命周期
	onMounted(() => {
		getUser()
		// 监听头像更新事件
		uni.$on('refresh', () => {
			getUser()  // 收到事件后重新获取用户信息
		})
	})

	// 在页面卸载时移除事件监听
	onUnmounted(() => {
		uni.$off('refresh')
	})
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f5f5;
	}

	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	// 头像区域
	.avatar-section {
		display: flex;
		justify-content: center;
		padding: 60rpx 0;
		background-color: #f5f5f5;
		margin-bottom: 40rpx;

		.avatar-container {
			position: relative;
			// 添加按钮样式重置
			padding: 0;
			background: none;
			border: none;
			margin: 0;
			// 添加以下样式来完全去除按钮外框
			outline: none;
			box-shadow: none;

			// 去除按钮的默认样式
			&::after {
				border: none;
			}

			// 确保按钮在各种状态下都没有边框
			&:focus,
			&:active,
			&:hover {
				outline: none;
				border: none;
				box-shadow: none;
			}

			.avatar-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				border: 4rpx solid #e0e0e0;
				object-fit: cover;
			}
		}
	}

	// 表单列表
	.form-list {
		background-color: #fff;
		margin: 0 30rpx 40rpx 30rpx;
		border-radius: 24rpx;

		.form-item {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 2rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			.label {
				width: 160rpx;
				font-size: 32rpx;
				color: #333;
			}

			.value {
				flex: 1;
				font-size: 32rpx;
				color: #666;
				text-align: right;
				margin-right: 20rpx;
			}

			.arrow {
				font-size: 32rpx;
				color: #c0c0c0;
			}
		}
	}

	// 保存按钮
	.save-btn-container {
		padding: 0 30rpx;

		.save-btn {
			width: 100%;
			height: 100rpx;
			background: linear-gradient(135deg, #ff6b9d, #ff8a9b);
			color: white;
			border: none;
			border-radius: 50rpx;
			font-size: 36rpx;
			font-weight: 500;
		}
	}

	// 弹窗样式
	.popup-content {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;

		.popup-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;
			border-bottom: 2rpx solid #e0e0e0;

			.popup-cancel {
				color: #666;
				font-size: 32rpx;
			}

			.popup-title {
				font-size: 36rpx;
				font-weight: 500;
				color: #333;
			}

			.popup-confirm {
				color: #007aff;
				font-size: 32rpx;
			}
		}

		.popup-body {
			padding: 40rpx;

			.input-field {
				width: 100%;
				height: 80rpx;
				border: 2rpx solid #e0e0e0;
				border-radius: 10rpx;
				padding: 0 30rpx;
				font-size: 32rpx;
				box-sizing: border-box;
			}

			.textarea-field {
				width: 100%;
				height: 200rpx;
				border: 2rpx solid #e0e0e0;
				border-radius: 10rpx;
				padding: 30rpx;
				font-size: 32rpx;
				resize: none;
				box-sizing: border-box;
			}

			.sex-options {
				display: flex;
				gap: 40rpx;

				.sex-option {
					flex: 1;
					text-align: center;
					padding: 24rpx;
					border: 2rpx solid #e0e0e0;
					border-radius: 10rpx;
					font-size: 32rpx;
					color: #666;

					&.active {
						background-color: #007aff;
						color: white;
						border-color: #007aff;
					}
				}
			}
		}
	}
</style>